<? if ($c = stack('name')) {
	
$s = component_settings($c);
	
$now = parse_today();
$expires = date("Y-m-d", mktime(0,0,0, $now['m'], $now['d'] + (int)$s['new_user_expires'], $now['y']));;

$_record = array('kind' => TK_RECOVER_PASS, 'expires' => $expires);

$res = array();



$email = h(trim(postdata('email')));

if (datafetch('db_item', 'cs_person', "email='$email'")) {

	$uuid = gccGetUUID();



	
// ** crafting ticket
	
	$res = array('email' => $email);
	$res = php2js($res);	

	$recp = 	$email;
	
	datafetch('db_insert', 'cs_ticket', array_merge($_record, array('id' => $uuid, 'data' => $res)));




// ** mail notification

	$tpl_tags = array(
		'expires' => date2str(parse_date($expires), context('lang')),
		'ticket_link' => "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]/$CONTEXT[lang_prefix]register/confirm-newpass/id-$uuid/",
		'base_url' => "$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]"
	);

	$se = array(); $re = array();	foreach($tpl_tags as $k => $v) { $se[] = '{'.$k.'}'; $re[] = $v; }

	$t = str_replace($se, $re, $s['mail_pass_recovery']);
	

	try {
		
		$subject = '=?utf-8?B?'.base64_encode( stripslashes($s['mail_pass_recovery_subj'])).'?=';
		
		$random_hash = md5(date('r', time())); 
		
		$headers = "From: \"=?utf-8?B?".base64_encode( stripslashes($s['mail_sender_name']))."?=\" <$s[mail_sender]>";
	
		$headers .= "\nX-Mailer: PHP/".phpversion();
		$headers .= "\nMIME-Version: 1.0";
		$headers .= "\nContent-Type: multipart/mixed; boundary=\"mixed-".$random_hash."\"";
		$headers .= "\nContent-Transfer-Encoding: base64";
	
		$body = chunk_split(base64_encode(stripslashes($t)));
	
	
		ob_start();

?>
--mixed-<?=$random_hash?>

Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: base64

<?=$body?>

--mixed-<?=$random_hash?>--

<?
	
		$body = ob_get_clean();
		
		if (@mail($recp, $subject, $body, $headers, '-f '.stripslashes($s['mail_sender'])))
			diags('<p class="success">Sent</p>');
		else
			throw new Exception('Not sent');
			
	//			exit( str_replace('<', '&lt;', json_encode(array("diags" => implode('', $GLOBALS['DIAGS'])))) );
	
	} catch(Exception $e) {
		diags('<p class="error">'.$e->getMessage().'</p>');
	}





	$res = array('email', true, '');
	
	print(json_encode($res));
	exit;

} else {

// debug('not validated');	
	
	$res = array('email', false, '');
		
	print(json_encode($res));
	exit;
}

unstack();
}